//
//  SettingViewController.m
//  MZJ
//
//  Created by XDD on 16/6/4.
//  Copyright © 2016年 XDD. All rights reserved.
//

#import "SettingViewController.h"
#import "SettingCell.h"
#import "AboutMyViewController.h"

@interface SettingViewController ()<UITableViewDelegate,UITableViewDataSource> {
    NSArray *nameArr;
}

@property (nonatomic, strong) UITableView *setting_TabelView;

@end

@implementation SettingViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.topBar.backgroundColor = [UIColor colorWithRed:253/255.0 green:179/255.0 blue:10/255.0 alpha:1];
    self.titleLabel.text = @"设置";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.backButton setTitle:@"" forState:UIControlStateNormal];
    
    self.setting_TabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 55, kWidth, kHeight - 55)];
    self.setting_TabelView.backgroundColor = [UIColor whiteColor];
    self.setting_TabelView.delegate = self;
    self.setting_TabelView.dataSource = self;
    [self.setting_TabelView registerNib:[UINib nibWithNibName:@"SettingCell" bundle:nil] forCellReuseIdentifier:@"settingCell"];
    self.setting_TabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.setting_TabelView];
    
    nameArr = @[@"清理缓存",@"关于"];
    [self getCacheSize];

}

- (void)viewDidAppear:(BOOL)animated {

    [super viewDidAppear:animated];
    
    [self.setting_TabelView reloadData];
}

//点击返回键
- (void)clickedBackButton:(UIButton *)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
    self.tabBarController.tabBar.hidden = NO;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 1) {
        return 0;
    }
    return 50;
}

//Header的高度
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section {

    if (section == 1) {
        return 150*XJVerticalMultiplier();
    }
    return 5*XJVerticalMultiplier();
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    UIView *head = [[UIView alloc]init];
    //    head.backgroundColor = [UIColor blackColor];
    if (section == 0) {
        head.frame = XJFlexibleFrame(CGRectMake(0, 0, 320, 5), NO);
        head.backgroundColor = [UIColor whiteColor];
        return head;
    }
    if (section == 1) {
        head.frame = XJFlexibleFrame(CGRectMake(0, 0, 320, 150), NO);
        head.backgroundColor = [UIColor whiteColor];
        
        UIButton *exitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        if ([[DataModel object].statu_Str intValue] == 0) {
            [exitBtn setTitle:@"退出" forState:UIControlStateNormal];

        }else {
            [exitBtn setTitle:@"登录" forState:UIControlStateNormal];
        }
        [exitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        exitBtn.frame = XJFlexibleFrame(CGRectMake(60, 70, 200, 25), NO);
        exitBtn.layer.cornerRadius = 3.0;
        exitBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        exitBtn.backgroundColor = [UIColor colorWithRed:253/255.0 green:179/255.0 blue:10/255.0 alpha:1];
        exitBtn.layer.masksToBounds = YES;
        [exitBtn addTarget:self action:@selector(exitBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [head addSubview:exitBtn];
        
        return head;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return nameArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    
    static NSString *identifier = @"settingCell";
    SettingCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (!cell) {
        
        cell = [[SettingCell alloc] initWithFrame:CGRectZero];
    }
    cell.myCache_Label.hidden = YES;
    if (section == 0) {
        cell.nameLabel.text = nameArr[indexPath.row];
        if (indexPath.row == 0) {
            cell.myCache_Label.hidden = NO;
            cell.myCache_Label.text = [self getCacheSize];
        }
    }
    
    
//    if (section == 1) {
//        cell.switchBtn.hidden = YES;
//    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            AboutMyViewController *aboutMyViewController = [[AboutMyViewController alloc]init];
            [self.navigationController pushViewController:aboutMyViewController animated:YES];
        }
        if (indexPath.row == 0) {
            
            NSFileManager *fileManager = [NSFileManager defaultManager];
                     //02.....
                     NSString *cacheFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
                     //03......
                     [fileManager removeItemAtPath:cacheFilePath error:nil];
            
                     //04刷新第一行单元格
                     NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
                     [self.setting_TabelView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            
                     //05 ：04和05使用其一即可
                    [self.setting_TabelView reloadData];//刷新表视图
            
            //清理缓存，清除模板
            NSString *extension = @"useDetail.txt";
//            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            for (int i = 0; i < paths.count; i++) {
                NSString *documentsDirectory = [paths objectAtIndex:i];
                
                NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
                NSEnumerator *e = [contents objectEnumerator];
                NSString *filename;
                while ((filename = [e nextObject])) {
                    
                    if (![filename   isEqualToString:extension]) {
                        
                        [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
                    }
                    
                }
                
            }
            [self waringAction:@"清除成功"];
        }
    }
}

- (void)exitBtnAction {
    if ([[DataModel object].statu_Str intValue] == 0) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"你确认要退出当前账号吗" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            
            //退出当前账号
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"user_token"];
            
            [[NSUserDefaults standardUserDefaults] synchronize];
            [DataModel object].userDetail = nil;
            [DataModel object].statu_Str = nil;
            
            // 清除本地配置数据
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            
            NSFileManager *fileMgr = [NSFileManager defaultManager];
            NSString *MapLayerDataPath = [documentsDirectory stringByAppendingPathComponent:@"useDetail.txt"];
            BOOL bRet = [fileMgr fileExistsAtPath:MapLayerDataPath];
            if (bRet) {
                //
                NSError *err;
                [fileMgr removeItemAtPath:MapLayerDataPath error:&err];
                
            }
            //            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"AUTOLOGIN"];
            self.tabBarController.tabBar.hidden = NO;
            [self.navigationController popViewControllerAnimated:YES];
            //            [[NSNotificationCenter defaultCenter] postNotificationName:@"denglu" object:nil];
            
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else {
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (NSString *)getCacheSize
 {
         //定义变量存储总的缓存大小
         long long sumSize = 0;
    
         //01.获取当前图片缓存路径
        NSString *cacheFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
    
         //02.创建文件管理对象
         NSFileManager *filemanager = [NSFileManager defaultManager];
    
             //获取当前缓存路径下的所有子路径
         NSArray *subPaths = [filemanager subpathsOfDirectoryAtPath:cacheFilePath error:nil];
    
             //遍历所有子文件
         for (NSString *subPath in subPaths) {
                     //1）.拼接完整路径
                 NSString *filePath = [cacheFilePath stringByAppendingFormat:@"/%@",subPath];
                     //2）.计算文件的大小
                 long long fileSize = [[filemanager attributesOfItemAtPath:filePath error:nil]fileSize];
                     //3）.加载到文件的大小
                 sumSize += fileSize;
             
             NSLog(@"%@",filePath);
             
             }
         float size_m = sumSize/(1024*1024);
     
//     NSLog(@"%@",[NSString stringWithFormat:@"%.2fM",size_m]);
         return [NSString stringWithFormat:@"%.2fM",size_m];
    
     }

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
